﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Agents.Data;

namespace Agents.Agent
{
    public partial class NotificationDetails : System.Web.UI.Page
    {
        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            GetDataSource();
        }

        /// <summary>
        /// Closes the popup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void closeBtn_Click(object sender, EventArgs e)
        {
            Response.Write("<script language='javascript'>self.close();</script>");
        }

        /// <summary>
        /// Deletes this notification
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>//function deletes the chosen product from the database.
        protected void dgNotifications_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            // Get notification Id
            int id = Int32.Parse(e.Item.Cells[0].Text);
            Queries queries = new Queries();
            queries.DeleteLocationBasedNotification(id);

            // Refresh the grid
            GetDataSource();
        }

        /// <summary>
        /// Takes care of the page indexing of the DataGrid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dgNotifications_PageIndexChanged(object sender, 
                                                DataGridPageChangedEventArgs e)
        {
            // Changing the data grid viewing to the selected index
            dgNotifications.CurrentPageIndex = e.NewPageIndex;

            // Binding the data grid data
            GetDataSource();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Set the data source (could not be done in the aspx because
        /// of a bug in asp.net).
        /// </summary>
        private void GetDataSource()
        {
            Queries queries = new Queries();

            // Get the notifications ids from the parameter and convert to int
            List<String> strNotificationIds =
                Request.QueryString["notificationsIds"].
                Split(new char[] { ',' }).ToList();
            List<int> notificationIds = new List<int>();
            strNotificationIds.ForEach((s) => notificationIds.Add(Int32.Parse(s)));

            // Build the data source
            dgNotifications.DataSource =
                queries.GetLocationBasedNotifications().
                Where((n) => notificationIds.Contains(n.Id));
            dgNotifications.DataBind();
        }

        #endregion
    }
}